//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.server;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

import tv.dyndns.kishibe.client.Service;
import tv.dyndns.kishibe.client.constant.Constant;
import tv.dyndns.kishibe.client.game.GameMode;
import tv.dyndns.kishibe.client.game.ProblemGenre;
import tv.dyndns.kishibe.client.game.ProblemType;
import tv.dyndns.kishibe.client.game.RandomFlag;
import tv.dyndns.kishibe.client.packet.NewAndOldProblems;
import tv.dyndns.kishibe.client.packet.PacketBbsResponse;
import tv.dyndns.kishibe.client.packet.PacketBbsThread;
import tv.dyndns.kishibe.client.packet.PacketChatData;
import tv.dyndns.kishibe.client.packet.PacketChatDataList;
import tv.dyndns.kishibe.client.packet.PacketGameStatus;
import tv.dyndns.kishibe.client.packet.PacketImageLink;
import tv.dyndns.kishibe.client.packet.PacketLinkData;
import tv.dyndns.kishibe.client.packet.PacketLogin;
import tv.dyndns.kishibe.client.packet.PacketMatchingData;
import tv.dyndns.kishibe.client.packet.PacketPlayerSummary;
import tv.dyndns.kishibe.client.packet.PacketProblem;
import tv.dyndns.kishibe.client.packet.PacketProblemCreationLog;
import tv.dyndns.kishibe.client.packet.PacketRankingData;
import tv.dyndns.kishibe.client.packet.PacketRatingDistribution;
import tv.dyndns.kishibe.client.packet.PacketReadyForGame;
import tv.dyndns.kishibe.client.packet.PacketRegistrationData;
import tv.dyndns.kishibe.client.packet.PacketResult;
import tv.dyndns.kishibe.client.packet.PacketRoomKey;
import tv.dyndns.kishibe.client.packet.PacketServerStatus;
import tv.dyndns.kishibe.client.packet.PacketTheme;
import tv.dyndns.kishibe.client.packet.PacketThemeModeEditor;
import tv.dyndns.kishibe.client.packet.PacketUserData;
import tv.dyndns.kishibe.client.packet.PacketWrongAnswer;
import tv.dyndns.kishibe.server.database.Database;
import tv.dyndns.kishibe.server.handwriting.Recognizable;
import tv.dyndns.kishibe.server.sns.SnsClient;
import tv.dyndns.kishibe.server.sns.SnsClients;
import tv.dyndns.kishibe.server.util.IntArray;
import tv.dyndns.kishibe.server.websocket.WebSocketServer;

import com.google.common.base.Objects;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.google.inject.name.Named;

@SuppressWarnings("serial")
@Singleton
public class ServiceImpl extends RemoteServiceServlet implements Service {
	private static final Logger logger = Logger.getLogger(ServiceImpl.class.toString());
	private static final File PROBLEM_CREATION_LOG_FILE = new File("/tmp/qmaclone/problem.log");
	private final Random random = new Random();
	private final ChatManager chatManager;
	private final NormalModeProblemManager normalModeProblemManager;
	private final ThemeModeProblemManager themeModeProblemManager;;
	private final GameManager gameManager;
	private final ServerStatusManager serverStatusManager;
	private final BadUserManager badUserManager;
	private final PlayerHistoryManager playerHistoryManager;
	private final VoteManager voteManager;
	private final Recognizable recognizer;
	private final ThemeModeEditorManager themeModeEditorManager;
	private final WebSocketServer webSocketServer;
	private final ImageManager imageManager;
	private final Database databse;
	private final PrefectureRanking prefectureRanking;
	private final RatingDistribution ratingDistribution;
	private final SnsClient snsClient;
	private final GameLogger gameLogger;

	/**
	 * Only for testing.
	 */
	public ServiceImpl() {
		Injector injector = Guice.createInjector(new QMACloneModule());
		this.chatManager = injector.getInstance(ChatManager.class);
		this.normalModeProblemManager = injector.getInstance(NormalModeProblemManager.class);
		this.themeModeProblemManager = injector.getInstance(ThemeModeProblemManager.class);
		this.gameManager = injector.getInstance(GameManager.class);
		this.serverStatusManager = injector.getInstance(ServerStatusManager.class);
		this.badUserManager = injector.getInstance(BadUserManager.class);
		this.playerHistoryManager = injector.getInstance(PlayerHistoryManager.class);
		this.voteManager = injector.getInstance(VoteManager.class);
		this.recognizer = injector.getInstance(Recognizable.class);
		this.themeModeEditorManager = injector.getInstance(ThemeModeEditorManager.class);
		this.webSocketServer = injector.getInstance(WebSocketServer.class);
		this.imageManager = injector.getInstance(ImageManager.class);
		this.databse = injector.getInstance(Database.class);
		this.prefectureRanking = injector.getInstance(PrefectureRanking.class);
		this.ratingDistribution = injector.getInstance(RatingDistribution.class);
		this.snsClient = injector.getInstance(SnsClients.class);
		this.gameLogger = injector.getInstance(GameLogger.class);
	}

	@Inject
	public ServiceImpl(ChatManager chatManager, NormalModeProblemManager normalModeProblemManager,
			ThemeModeProblemManager themeModeProblemManager, GameManager gameManager,
			ServerStatusManager serverStatusManager, BadUserManager badUserManager,
			PlayerHistoryManager playerHistoryManager, VoteManager voteManager,
			Recognizable recognizer, ThemeModeEditorManager themeModeEditorManager,
			WebSocketServer webSocketServer, ImageManager imageManager, Database databse,
			PrefectureRanking prefectureRanking, RatingDistribution ratingDistribution,
			@Named("SnsClients") SnsClient snsClient, GameLogger gameLogger) {
		this.chatManager = chatManager;
		this.normalModeProblemManager = normalModeProblemManager;
		this.themeModeProblemManager = themeModeProblemManager;
		this.gameManager = gameManager;
		this.serverStatusManager = serverStatusManager;
		this.badUserManager = badUserManager;
		this.playerHistoryManager = playerHistoryManager;
		this.voteManager = voteManager;
		this.recognizer = recognizer;
		this.themeModeEditorManager = themeModeEditorManager;
		this.webSocketServer = webSocketServer;
		this.imageManager = imageManager;
		this.databse = databse;
		this.prefectureRanking = prefectureRanking;
		this.ratingDistribution = ratingDistribution;
		this.snsClient = snsClient;
		this.gameLogger = gameLogger;

		// テーマモードのTwitter通知タイミング調整
		ThreadPool.get().scheduleWithFixedDelay(commandUpdateThemeModeNotificationCounter, 1, 1,
				TimeUnit.SECONDS);
		try {
			webSocketServer.start();
		} catch (Exception e) {
			logger.log(Level.WARNING, "WebSocketの開始に失敗しました", e);
		}
	}

	@Override
	public String processCall(String payload) {
		// すべての例外を補足してログに出力する
		try {
			return super.processCall(payload);
		} catch (Exception e) {
			logger.log(Level.WARNING, "不明なエラーが発生しました", e);
			throw Throwables.propagate(e);
		}
	}

	@Override
	public void destroy() {
		try {
			webSocketServer.stop();
		} catch (Exception e) {
			logger.log(Level.WARNING, "WebSocketの停止に失敗しました", e);
		}
		try {
			webSocketServer.join();
		} catch (InterruptedException e) {
			logger.log(Level.WARNING, "WebSocketの停止待機に失敗しました", e);
		}
		ThreadPool.get().shutdown();
		super.destroy();
	}

	@Override
	public PacketServerStatus getServerStatus() throws Exception {
		return serverStatusManager.getServerStatus();
	}

	@Override
	public PacketLogin login(int userCode) throws Exception {
		serverStatusManager.login();
		serverStatusManager.keepAlive(userCode);
		PacketLogin login = new PacketLogin();
		login.removeAddress = getRemoteAddress();
		return login;
	}

	@Override
	public void keepAlive(int userCode) throws Exception {
		serverStatusManager.keepAlive(userCode);
	}

	// プレイヤー情報を登録する
	private Object lockObjectRegister = new Object();

	@Override
	public PacketRegistrationData register(PacketPlayerSummary playerSummary,
			Set<ProblemGenre> genres, Set<ProblemType> types, String greeting, GameMode gameMode,
			String roomName, String theme, String imageFileName, int classLevel,
			int difficultSelect, int rating, int userCode, int volatility, int playCount,
			NewAndOldProblems newAndOldProblems, boolean publicEvent) throws Exception {
		gameLogger.write(Objects
				.toStringHelper(this)
				.add("method", "register")
				.add("userCode", userCode)
				.toString());

		playerHistoryManager.push(playerSummary);

		PlayerStatus status;
		synchronized (lockObjectRegister) {
			Game session = gameManager.getMatchingSession(gameMode, roomName, classLevel, theme,
					genres, types, publicEvent, serverStatusManager, userCode, getRemoteAddress(),
					badUserManager);
			status = session.addPlayer(playerSummary, genres, types, greeting, imageFileName,
					classLevel, difficultSelect, rating, userCode, volatility, playCount,
					newAndOldProblems);
		}

		PacketRegistrationData data = new PacketRegistrationData();
		data.playerId = status.getPlayerId();
		data.playerListIndex = status.getPlayerListId();
		data.sessionId = status.getSessionId();

		return data;
	}

	// マッチング
	@Override
	public PacketMatchingData getMatchingData(int sessionId) throws Exception {
		return gameManager.getSession(sessionId).getMatchingData();
	}

	// 強制的にゲームをスタートさせる
	@Override
	public int requestSkip(int sessionId, int playerListId) throws Exception {
		Game session = gameManager.getSession(sessionId);
		session.requestStartingGame(playerListId);
		return session.getNumberOfPlayer();
	}

	// ゲーム開始待機
	// ゲームの開始を待つ
	@Override
	public PacketReadyForGame waitForGame(int sessionId) throws Exception {
		return gameManager.getSession(sessionId).getReadyForGameStatus();
	}

	// 問題を取得する
	@Override
	public List<PacketProblem> getProblem(int sessionId) throws Exception {
		return gameManager.getSession(sessionId).getProblem();
	}

	// 他のプレイヤーの名前を取得する
	@Override
	public List<PacketPlayerSummary> getPlayerSummaries(int sessionId) throws Exception {
		return gameManager.getSession(sessionId).getPlayerSummaries();
	}

	@Override
	public void sendAnswer(int sessionId, int playerListId, String answer, int userCode,
			int responseTime) throws Exception {
		gameManager.getSession(sessionId).receiveAnswer(playerListId, answer);
		gameLogger.write(Objects
				.toStringHelper(this)
				.add("method", "sendAnswer")
				.add("sessionId", sessionId)
				.add("playerListId", playerListId)
				.add("answer",
						Arrays.deepToString(Objects.firstNonNull(answer, "").split(
								Constant.DELIMITER_GENERAL)))
				.add("userCode", userCode)
				.add("responseTime", responseTime)
				.add("remoteAddress", getRemoteAddress())
				.toString());
	}

	@Override
	public void notifyTimeUp(int sessionId, int playerListId, int userCode) throws Exception {
		gameLogger.write(Objects
				.toStringHelper(this)
				.add("method", "notifyTimeUp")
				.add("sessionId", sessionId)
				.add("playerListId", playerListId)
				.add("userCode", userCode)
				.add("remoteAddress", getRemoteAddress())
				.toString());
	}

	@Override
	public void notifyGameFinished(int userCode, int oldRating, int newRating) throws Exception {
		gameLogger.write(Objects
				.toStringHelper(this)
				.add("method", "notifyGameFinished")
				.add("userCode", userCode)
				.add("oldRating", oldRating)
				.add("newRating", newRating)
				.add("remoteAddress", getRemoteAddress())
				.toString());
	}

	// ゲームの進行状態を取得する
	@Override
	public PacketGameStatus getGameStatus(int sessionId) throws Exception {
		Game session = gameManager.getSession(sessionId);
		return session.getGameStatus();
	}

	@Override
	public void keepAliveGame(int sessionId, int playerListId) throws Exception {
		Game session = gameManager.getSession(sessionId);
		session.keepAlive(playerListId);
	}

	// 結果表示
	// 最終結果を取得する
	@Override
	public List<PacketResult> getResult(int sessionId) throws Exception {
		return gameManager.getSession(sessionId).getPacketResult();
	}

	// チャットにメッセージを送信する
	@Override
	public void sendMessageToChat(PacketChatData chatData) throws Exception {
		if (badUserManager.isLimitedUser(chatData.userCode, getRemoteAddress())) {
			badUserManager.addLimitedUser(chatData.userCode, getRemoteAddress());
		}

		// ロックはChatManager側で行う
		chatManager.write(chatData, getRemoteAddress());
	}

	@Override
	public PacketChatDataList receiveMessageFromChat(int lastestResId) throws Exception {
		// ロックはChatManager側で行う
		return chatManager.read(lastestResId);
	}

	// 問題を投稿する
	private final Object fileLock = new Object();

	@Override
	public int uploadProblem(final PacketProblem problem, final int userCode) throws Exception {
		final String remoteAddress = getRemoteAddress();

		ThreadPool.get().execute(new Runnable() {
			@Override
			public void run() {
				synchronized (fileLock) {
					try {
						Files.createParentDirs(PROBLEM_CREATION_LOG_FILE);
					} catch (IOException e) {
						logger.log(Level.WARNING, "問題作成ログディレクトリの作成に失敗しました", e);
					}
					try (PrintStream stream = new PrintStream(new BufferedOutputStream(
							new FileOutputStream(PROBLEM_CREATION_LOG_FILE, true)), false, "MS932")) {
						stream.println(problem.toString());
						stream.println(userCode + "\t" + remoteAddress + "\t"
								+ Calendar.getInstance().getTime());
					} catch (Exception e) {
						logger.log(Level.WARNING, "問題作成ログの書き込みに失敗しました", e);
					}
				}
			}
		});

		if (badUserManager.isLimitedUser(userCode, remoteAddress)) {
			badUserManager.addLimitedUser(userCode, remoteAddress);
			if (problem.id == -1) {
				return normalModeProblemManager.getNumberOfProblem() + 1;
			} else {
				return problem.id;
			}
		}

		final int problemID;

		if (problem.id == -1) {
			problemID = normalModeProblemManager.addProblem(problem);
		} else {
			normalModeProblemManager.updateProblem(problem);
			problemID = problem.id;
		}

		ThreadPool.get().execute(new Runnable() {
			@Override
			public void run() {
				try {
					databse.addCreationLog(problemID, userCode, remoteAddress);
				} catch (SQLException e) {
					logger.log(Level.WARNING, "問題作成ログの保存に失敗しました", e);
				}
			}
		});

		// SNSに投稿
		ThreadPool.get().execute(new Runnable() {
			@Override
			public void run() {
				snsClient.postProblem(problem);
			}
		});

		return problemID;
	}

	// 問題を取得する
	@Override
	public List<PacketProblem> getProblemList(List<Integer> problemIds) throws Exception {
		return databse.getProblem(problemIds);
	}

	@Override
	public int[][] getStatisticsOfProblemCount() throws Exception {
		return normalModeProblemManager.getTableProblemCount();
	}

	@Override
	public int[][] getStatisticsOfAccuracyRate() throws Exception {
		return normalModeProblemManager.getTableProblemRatio();
	}

	@Override
	public List<PacketProblem> searchProblem(String query, String creator,
			boolean creatorPerfectMatching, Set<ProblemGenre> genres, Set<ProblemType> types,
			Set<RandomFlag> randomFlags) throws Exception {
		return databse.searchProblem(query, creator, creatorPerfectMatching, genres, types,
				randomFlags);
	}

	@Override
	public List<PacketProblem> searchSimilarProblem(PacketProblem problem) throws Exception {
		return databse.searchSimilarProblemFromDatabase(problem);
	}

	@Override
	public int getNewUserCode() throws Exception {
		int userCode;
		do {
			userCode = random.nextInt(100000000);
		} while (databse.isUsedUserCode(userCode));
		return userCode;
	}

	@Override
	public void addProblemIdsToReport(int userCode, List<Integer> problemIds) throws Exception {
		databse.addProblemIdsToReport(userCode, problemIds);
	}

	@Override
	public void removeProblemIDFromReport(int userCode, int problemID) throws Exception {
		databse.removeProblemIdFromReport(userCode, problemID);
	}

	@Override
	public void clearProblemIDFromReport(int userCode) throws Exception {
		databse.clearProblemIdFromReport(userCode);
	}

	@Override
	public List<PacketProblem> getUserProblemReport(int userCode) throws Exception {
		return databse.getUserProblemReport(userCode);
	}

	@Override
	public PacketUserData loadUserData(int userCode) throws Exception {
		return databse.getUserDataByUserCode(userCode);
	}

	@Override
	public void saveUserData(PacketUserData userData) throws Exception {
		databse.setUserData(userData);
	}

	@Override
	public List<PacketUserData> getLoginUsers() throws Exception {
		return serverStatusManager.getLoginUsers();
	}

	@Override
	public List<PacketWrongAnswer> getWrongAnswers(int problemID) throws Exception {
		return databse.getPlayerAnswers(problemID);
	}

	@Override
	public void removePlayerAnswers(int problemID) throws Exception {
		databse.removePlayerAnswers(problemID);
	}

	@Override
	public List<List<PacketRankingData>> getRankingData() throws Exception {
		return databse.getRankingData();
	}

	@Override
	public void addIgnoreUserCode(int userCode, int targetUserCode) throws Exception {
		badUserManager.addIgnoreUserCode(userCode, targetUserCode);
	}

	@Override
	public void removeIgnoreUserCode(int userCode, int targetUserCode) throws Exception {
		badUserManager.removeIgnoreUserCode(userCode, targetUserCode);
	}

	@Override
	public List<PacketProblemCreationLog> getProblemCreationLog(int problemId) throws Exception {
		return databse.getProblemCreationHistory(problemId);
	}

	@Override
	public List<PacketBbsResponse> getBbsResponses(int threadId, int count) throws Exception {
		return databse.getBbsResponses(threadId, count);
	}

	@Override
	public List<PacketBbsThread> getBbsThread(int start, int count) throws Exception {
		return databse.getBbsThread(start, count);
	}

	@Override
	public void buildBbsThread(PacketBbsThread thread, PacketBbsResponse response) throws Exception {
		response.remoteAddress = getRemoteAddress();

		if (badUserManager.isLimitedUser(response.userCode, response.remoteAddress)) {
			badUserManager.addLimitedUser(response.userCode, response.remoteAddress);
			return;
		}
		databse.buildBbsThread(thread, response);
	}

	@Override
	public void writeToBbs(PacketBbsResponse response, boolean age) throws Exception {
		response.remoteAddress = getRemoteAddress();

		if (badUserManager.isLimitedUser(response.userCode, response.remoteAddress)) {
			badUserManager.addLimitedUser(response.userCode, response.remoteAddress);
			return;
		}

		databse.writeToBbs(response, age);
	}

	@Override
	public int getNumberOfBbsThreads() throws Exception {
		return databse.getNumberOfBbsThread();
	}

	@Override
	public void addLinkData(PacketLinkData linkData) throws Exception {
		databse.addLinkData(linkData);
	}

	@Override
	public List<PacketLinkData> getLinkDatas(int start, int count) throws Exception {
		return databse.getLinkDatas(start, count);
	}

	@Override
	public int getNumberOfLinkDatas() throws Exception {
		return databse.getNumberOfLinkDatas();
	}

	@Override
	public void removeLinkData(int id) throws Exception {
		databse.removeLinkData(id);
	}

	@Override
	public void updateLinkData(PacketLinkData linkData) throws Exception {
		databse.updateLinkData(linkData);
	}

	@Override
	public int[][] getPrefectureRanking() throws Exception {
		return prefectureRanking.get();
	}

	@Override
	public void addRatingHistory(int userCode, int rating) throws Exception {
		databse.addRatingHistory(userCode, rating);
	}

	@Override
	public List<Integer> getRatingHistory(int userCode) throws Exception {
		return databse.getRatingHistory(userCode);
	}

	@Override
	public PacketRatingDistribution getRatingDistribution() throws Exception {
		return ratingDistribution.get();
	}

	@Override
	public List<List<String>> getThemeModeThemes() throws Exception {
		return themeModeProblemManager.getThemes();
	}

	@Override
	public Map<String, List<PacketRankingData>> getThemeModeRanking() throws Exception {
		return databse.getThemeModeRankingData();
	}

	@Override
	public List<PacketRoomKey> getEventRooms() throws Exception {
		return gameManager.getEventRooms();
	}

	@Override
	public void voteToProblem(int userCode, int problemId, boolean good, String feedback,
			String playerName) throws Exception {
		voteManager.vote(userCode, problemId, good, feedback, playerName, getRemoteAddress(),
				badUserManager);
	};

	@Override
	public String[] recognizeHandwriting(double[][][] strokes) throws Exception {
		return recognizer.recognize(strokes);
	}

	@Override
	public Set<String> getAvailableChalactersForHandwriting() throws Exception {
		return recognizer.getAvailableCharacters();
	}

	@Override
	public void clearProblemFeedback(int problemId) throws Exception {
		databse.clearProblemFeedback(problemId);
	}

	@Override
	public List<String> getProblemFeedback(int problemId) throws Exception {
		return databse.getProblemFeedback(problemId);
	}

	@Override
	public List<PacketTheme> getThemes() throws Exception {
		Map<String, List<String>> themeModeQueries = databse.getThemeModeQueries();
		Map<String, IntArray> themeModeProblems = themeModeProblemManager.getThemesAndProblems();

		List<PacketTheme> themes = Lists.newArrayList();
		for (Entry<String, List<String>> entry : themeModeQueries.entrySet()) {
			PacketTheme theme = new PacketTheme();
			theme.name = entry.getKey();
			theme.queries = entry.getValue();
			IntArray problemIds = themeModeProblems.get(theme.name);
			if (problemIds != null) {
				theme.numberOfProblems = problemIds.size();
			}
			themes.add(theme);
		}

		Collections.sort(themes, new Comparator<PacketTheme>() {
			@Override
			public int compare(PacketTheme o1, PacketTheme o2) {
				return o1.name.compareTo(o2.name);
			}
		});

		return themes;
	}

	private Map<String, AtomicInteger> themeModeNotificationCounter = new HashMap<String, AtomicInteger>();
	private transient final Runnable commandUpdateThemeModeNotificationCounter = new Runnable() {
		@Override
		public void run() {
			synchronized (themeModeNotificationCounter) {
				Set<Entry<String, AtomicInteger>> entrySet = themeModeNotificationCounter
						.entrySet();
				for (Entry<String, AtomicInteger> entry : entrySet) {
					if (entry.getValue().decrementAndGet() >= 0) {
						continue;
					}

					final String theme = entry.getKey();
					ThreadPool.get().execute(new Runnable() {
						@Override
						public void run() {
							snsClient.postThemeModeUpdate(theme);
						}
					});

					entrySet.remove(entry);
				}
			}
		}
	};

	private static final int THEME_MODE_NOTIFICATION_WAIT = 60;

	@Override
	public void addThemeModeQuery(String theme, String query) throws Exception {
		databse.addThemeModeQuery(theme, query);

		synchronized (themeModeNotificationCounter) {
			themeModeNotificationCounter
					.put(theme, new AtomicInteger(THEME_MODE_NOTIFICATION_WAIT));
		}
	}

	@Override
	public void removeThemeModeQuery(String theme, String query) throws Exception {
		databse.removeThemeModeQuery(theme, query);

		synchronized (themeModeNotificationCounter) {
			themeModeNotificationCounter
					.put(theme, new AtomicInteger(THEME_MODE_NOTIFICATION_WAIT));
		}
	}

	@Override
	public boolean isThemeModeEditor(int userCode) throws Exception {
		return themeModeEditorManager.isThemeModeEditor(userCode);
	}

	@Override
	public void applyThemeModeEditor(int userCode, String text) throws Exception {
		themeModeEditorManager.applyThemeModeEditor(userCode, text);
	}

	@Override
	public void acceptThemeModeEditor(int userCode) throws Exception {
		themeModeEditorManager.acceptThemeModeEditor(userCode);
	}

	@Override
	public void rejectThemeModeEditor(int userCode) throws Exception {
		themeModeEditorManager.rejectThemeModeEditor(userCode);
	}

	@Override
	public List<PacketThemeModeEditor> getThemeModeEditors() throws Exception {
		return themeModeEditorManager.getThemeModeEditors();
	}

	@Override
	public boolean isApplyingThemeModeEditor(int userCode) throws Exception {
		return themeModeEditorManager.isApplyingThemeModeEditor(userCode);
	}

	private String getRemoteAddress() throws Exception {
		return getThreadLocalRequest().getRemoteAddr();
	}

	@Override
	public Set<Integer> getLimitedUserCodes() throws Exception {
		return databse.getLimitedUserCodes();
	}

	@Override
	public void removeLimitedUserCode(int userCode) throws Exception {
		databse.removeLimitedUserCode(userCode);
	}

	@Override
	public void addLimitedUserCode(int userCode) throws Exception {
		databse.addLimitedUserCode(userCode);
	}

	@Override
	public void clearLimitedUserCode() throws Exception {
		databse.clearLimitedUserCodes();
	}

	@Override
	public Set<String> getLimitedRemoteAddresses() throws Exception {
		return databse.getLimitedRemoteAddresses();
	}

	@Override
	public void removeLimitedRemoteAddress(String remoteAddress) throws Exception {
		databse.removeLimitedRemoteAddress(remoteAddress);
	}

	@Override
	public void addLimitedRemoteAddress(String remoteAddress) throws Exception {
		if (remoteAddress.equals("127.0.0.1")) {
			return;
		}
		databse.addLimitedRemoteAddress(remoteAddress);
	}

	@Override
	public void clearLimitedRemoteAddress() throws Exception {
		databse.clearLimitedRemoteAddresses();
	}

	@Override
	public int getNumberOfChatLog() throws Exception {
		return databse.getNumberOfChatLog();
	}

	@Override
	public int getChatLogId(int year, int month, int day, int hour, int minute, int second)
			throws Exception {
		return databse.getChatLogId(year, month, day, hour, minute, second);
	}

	@Override
	public List<PacketChatData> getChatLog(int start) throws Exception {
		return databse.getChatLog(start);
	}

	@Override
	public List<PacketImageLink> getWrongImageLinks() throws Exception {
		return imageManager.getErrorImageLinks();
	}

	@Override
	protected void checkPermutationStrongName() throws SecurityException {
	}

	@Override
	public boolean canUploadProblem(int userCode) throws Exception {
		long dateFrom = System.currentTimeMillis() - 60 * 60 * 1000;
		return databse.getNumberOfCreationLogWithMachineIp(getRemoteAddress(), dateFrom) <= Constant.MAX_NUMBER_OF_CREATION_PER_HOUR
				&& databse.getNumberOfCreationLogWithUserCode(userCode, dateFrom) <= Constant.MAX_NUMBER_OF_CREATION_PER_HOUR;
	}
}
